import re

import pyframe
from pyframe import values
from pyframe import sources
from pyframe.exceptions.xml_serializable_exception import XmlSerializableException

class Block(object):

	_methodRE = re.compile(r'(\w)([A-Z])')

	_node = None

	def __init__(self, node):

		self._node = node

	def process(self):

		if(not self._checkGuard()):
			return None;

		method = self._node.get('method');

		return self._processTemplate(getattr(__import__(name = 'pyframe.block_methods.' + Block._methodRE.sub(r'\1_\2', method).lower(), fromlist = [method]), method)(self._extractMethodParams()).run())

	def _extractMethodParams(self):

		return dict([
			(nodeParam.get('name'), values.create(nodeParam.get('type'), sources.create(nodeParam.get('source'), nodeParam.text).get()))
			for nodeParam in self._node.findall('{%s}param' % pyframe.NAME_SPACE)
				if nodeParam.get('name')
			])

	def _checkGuard(self):

		return True

	def _processTemplate(self, blockResult):

		if(not self._node.get('template')):
			return blockResult

		xmlHelper = pyframe.getXmlHelper()

		try:

			return str(
				xmlHelper.processXSLT(
					xmlHelper.createNodeFromString(blockResult).getroottree(),
					pyframe.getFrontDirectory() + self._node.get('template')
					)['document'])

		except Exception, instance:
			raise XmlSerializableException(instance.message, 'block-template-not-found')